import { getCategory } from '@/apis';
import { ICategory } from '@/types';
import { getUserInfo } from '@/utils';
import { useCallback, useEffect, useMemo } from 'react';
import { atom, useRecoilState } from 'recoil';

interface ICategoryState {
    /**
     * if inited
     */
    init: boolean;
    /**
     * category list
     */
    data: ICategory[];
}

/**
 * categroy data
 */
const categroyState = atom<ICategoryState>({
    key: 'categroy',
    default: {
        init: false,
        data: []
    }
});

/**
 * 商品大类
 */
function useCategory() {
    const [val, setVal] = useRecoilState(categroyState);
    const user = useMemo(() => getUserInfo(), []);

    const update = useCallback(
        () => {
            getCategory({
                brandID: user.brandID
            }).then(res => {
                setVal({
                    init: true,
                    data: res.data
                });
            });
        }, 
        []
    );

    useEffect(() => {
        if (!val?.init) {
            update();
        }
    }, []);

    const res: [
        ICategory[],
        () => void
    ] = [
        val.data,
        update
    ];

    return res;
}


export {
    categroyState,
    useCategory
};
